package rcs34.android.Namedays.Widget;

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

import rcs34.android.Namedays.DBHelper;
import rcs34.android.Namedays.GApp;
import rcs34.android.Namedays.R;
import rcs34.android.Namedays.Activity.A_Namedays;
import rcs34.android.libs.HSVOPicker.HSVOPicker;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.GradientDrawable;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.widget.RemoteViews;

public class WidgetService extends IntentService {
  private final int HISTORY = 1;
  private final int FUTURE = 20;
  private boolean firstOne = true;
  
  private HSVOPicker hsvResolver;
  
  public WidgetService() {
    super("WidgetService");
  }
  
  @Override
  public void onHandleIntent(Intent _intent) {
    AppWidgetManager wm = AppWidgetManager.getInstance(this
        .getApplicationContext());
    int[] allWidgetIds = _intent
        .getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
    
    hsvResolver = new HSVOPicker(this);
    firstOne = true;
    for (int widgetId : allWidgetIds) {
      // Create some random data
      RemoteViews widgetView = new RemoteViews(GApp.packageName,
          R.layout.widget);
      wm.updateAppWidget(widgetId, widgetView);
      fillWidget(widgetView, widgetId);
      // Register an onClickListener
      Intent intent = new Intent(getApplicationContext(), A_Namedays.class);
      intent.setAction("WidgetClick" + widgetId);
      intent.putExtra(GApp.EXTRA_WID, widgetId);
      PendingIntent pendingIntent = PendingIntent
          .getActivity(getApplicationContext(), 0, intent,
              PendingIntent.FLAG_CANCEL_CURRENT);
      widgetView.setOnClickPendingIntent(R.id.view_container, pendingIntent);
      wm.updateAppWidget(widgetId, widgetView);
    }
    hsvResolver = null;
  }
  
  private Bitmap createGradient(String _topHSV, String _botHSV, int _height,
      boolean _useTransparency) {
    int top = hsvResolver.resolve(_topHSV);
    int bot = hsvResolver.resolve(_botHSV);
    if (!_useTransparency) {
      top |= 0xFF000000;
      bot |= 0xFF000000;
    }
    GradientDrawable drawable = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM, new int[] { top, bot });
    // drawable.setAlpha(255);
    drawable.setBounds(0, 0, 1, _height);
    // drawable.setCornerRadius(2.0f);
    Bitmap bitmap = Bitmap.createBitmap(1, _height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.draw(canvas);
    return bitmap;
  }
  
  private void fillWidget(RemoteViews _remoteViews, int _widgetId) {
    SharedPreferences prefs = GApp.getWidgetPreferences(_widgetId);
    String table = prefs.getString(getString(R.string.prefCalendar),
        getString(R.string.dTable));
    boolean displayDate = prefs.getBoolean(getString(R.string.prefDisplayDate),
        GApp.dDisplayDate);
    boolean useTransparency = prefs.getBoolean(
        getString(R.string.prefUseTransparency), true);
    boolean displayFlag = prefs.getBoolean(
        getString(R.string.prefDisplayFlag), false);
    int fontSize = Integer.parseInt(prefs.getString(
        getString(R.string.prefFontSize), GApp.dFontSize));
    int linesPerDate = Integer.parseInt(prefs
        .getString(getString(R.string.prefLinesPerDate),
            getString(R.string.dLinesPerDate)));
    String c_aDayFont = prefs.getString(getString(R.string.prefADayColorFont),
        GApp.dcADayFont);
    String c_aDayTop = prefs.getString(getString(R.string.prefADayColorTop),
        GApp.dcADayTop);
    String c_aDayBottom = prefs.getString(
        getString(R.string.prefADayColorBottom), GApp.dcADayBottom);
    String c_nDayFont = prefs.getString(getString(R.string.prefNDayColorFont),
        GApp.dcNDayFont);
    String c_nDayTop = prefs.getString(getString(R.string.prefNDayColorTop),
        GApp.dcNDayTop);
    String c_nDayBottom = prefs.getString(
        getString(R.string.prefNDayColorBottom), GApp.dcNDayBottom);
    int aDayColor = hsvResolver.resolve(c_aDayFont);
    int namedayColor = hsvResolver.resolve(c_nDayFont);
    if (!useTransparency) {
      aDayColor |= 0xFF000000;
      namedayColor |= 0xFF000000;
    }
    int layoutId = R.layout.wdaymiddle_1;
    int heightId = R.dimen.height_middle_1;
    switch (fontSize) {
    case 1:
      switch (linesPerDate) {
      case 1:
        layoutId = R.layout.wdaytiny_1;
        heightId = R.dimen.height_tiny_1;
        break;
      case 2:
        layoutId = R.layout.wdaytiny_2;
        heightId = R.dimen.height_tiny_2;
        break;
      case 3:
        layoutId = R.layout.wdaytiny_3;
        heightId = R.dimen.height_tiny_3;
        break;
      case 5:
        layoutId = R.layout.wdaytiny_5;
        heightId = R.dimen.height_tiny_5;
        break;
      case 7:
        layoutId = R.layout.wdaytiny_7;
        heightId = R.dimen.height_tiny_7;
        break;
      }
      break;
    case 2:
      switch (linesPerDate) {
      case 1:
        layoutId = R.layout.wdaysmall_1;
        heightId = R.dimen.height_small_1;
        break;
      case 2:
        layoutId = R.layout.wdaysmall_2;
        heightId = R.dimen.height_small_2;
        break;
      case 3:
        layoutId = R.layout.wdaysmall_3;
        heightId = R.dimen.height_small_3;
        break;
      case 5:
        layoutId = R.layout.wdaysmall_5;
        heightId = R.dimen.height_small_5;
        break;
      case 7:
        layoutId = R.layout.wdaysmall_7;
        heightId = R.dimen.height_small_7;
        break;
      }
      break;
    case 3:
      switch (linesPerDate) {
      case 1:
        layoutId = R.layout.wdaymiddle_1;
        heightId = R.dimen.height_middle_1;
        break;
      case 2:
        layoutId = R.layout.wdaymiddle_2;
        heightId = R.dimen.height_middle_2;
        break;
      case 3:
        layoutId = R.layout.wdaymiddle_3;
        heightId = R.dimen.height_middle_3;
        break;
      case 5:
        layoutId = R.layout.wdaymiddle_5;
        heightId = R.dimen.height_middle_5;
        break;
      case 7:
        layoutId = R.layout.wdaymiddle_7;
        heightId = R.dimen.height_middle_7;
        break;
      }
      break;
    case 4:
      switch (linesPerDate) {
      case 1:
        layoutId = R.layout.wdaylarge_1;
        heightId = R.dimen.height_large_1;
        break;
      case 2:
        layoutId = R.layout.wdaylarge_2;
        heightId = R.dimen.height_large_2;
        break;
      case 3:
        layoutId = R.layout.wdaylarge_3;
        heightId = R.dimen.height_large_3;
        break;
      case 5:
        layoutId = R.layout.wdaylarge_5;
        heightId = R.dimen.height_large_5;
        break;
      case 7:
        layoutId = R.layout.wdaylarge_7;
        heightId = R.dimen.height_large_7;
        break;
      }
      break;
    case 5:
      switch (linesPerDate) {
      case 1:
        layoutId = R.layout.wdayhuge_1;
        heightId = R.dimen.height_huge_1;
        break;
      case 2:
        layoutId = R.layout.wdayhuge_2;
        heightId = R.dimen.height_huge_2;
        break;
      case 3:
        layoutId = R.layout.wdayhuge_3;
        heightId = R.dimen.height_huge_3;
        break;
      case 5:
        layoutId = R.layout.wdayhuge_5;
        heightId = R.dimen.height_huge_5;
        break;
      case 7:
        layoutId = R.layout.wdayhuge_7;
        heightId = R.dimen.height_huge_7;
        break;
      }
      break;
    }
    int height = getResources().getDimensionPixelSize(heightId);
    Bitmap aDayBackground = createGradient(c_aDayTop, c_aDayBottom, height,
        useTransparency);
    Bitmap namedayBackground = createGradient(c_nDayTop, c_nDayBottom, height,
        useTransparency);
    SimpleDateFormat sdf = null;
    if (displayDate) {
      sdf = new SimpleDateFormat(getString(R.string.dateFormat));
    }
    GregorianCalendar today = new GregorianCalendar();
    today.add(GregorianCalendar.DAY_OF_MONTH, -HISTORY);
    _remoteViews.removeAllViews(R.id.view_container);
    DBHelper dbHelper = new DBHelper(table);
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    for (int i = 0; i < (HISTORY + FUTURE + 1); i++) {
      String result = "";
      Cursor cursor = dbHelper.findByDate(db, today);
      cursor.moveToFirst();
      while (!cursor.isAfterLast()) {
        result += cursor.getString(0);
        cursor.moveToNext();
        if (!cursor.isAfterLast()) {
          result += ", ";
        }
      }
      cursor.close();
      RemoteViews theDay = new RemoteViews(GApp.packageName, layoutId);
      if (!displayDate) {
        // System.out.println("Setting to zero");
        theDay.removeAllViews(R.id.w_dateContainer);
      } else {
        theDay.setTextViewText(R.id.w_date, sdf.format(today.getTime()));
      }
      if (i == HISTORY) {
        theDay.setImageViewBitmap(R.id.background, namedayBackground);
        theDay.setTextColor(R.id.w_name, namedayColor);
        if (displayDate) {
          theDay.setTextColor(R.id.w_date, namedayColor);
        }
        int position = today.get(GregorianCalendar.DAY_OF_YEAR) - 1;
        if (!GApp.isALeepYear) {
          if (today.after(new GregorianCalendar(today
              .get(GregorianCalendar.YEAR), GregorianCalendar.FEBRUARY, 28, 23,
              59))) {
            position++;
          }
        }
        if (firstOne) {
          firstOne = false;
          GApp.setPosition(position);
        }
      } else {
        theDay.setImageViewBitmap(R.id.background, aDayBackground);
        theDay.setTextColor(R.id.w_name, aDayColor);
        if (displayDate) {
          theDay.setTextColor(R.id.w_date, aDayColor);
        }
      }
      theDay.setTextViewText(R.id.w_name, result);
      _remoteViews.addView(R.id.view_container, theDay);
      today.add(GregorianCalendar.DAY_OF_MONTH, 1);
    }
    db.close();
    _remoteViews.removeAllViews(R.id.w_flag_container);
    if(displayFlag && GApp.flags.containsKey(table)){
      Bitmap flag=BitmapFactory.decodeResource(GApp.context.getResources(), GApp.flags.get(table));
      RemoteViews flagView=new RemoteViews(GApp.packageName,R.layout.w_flagview);
      flagView.setImageViewBitmap(R.id.w_flag, flag);
      _remoteViews.addView(R.id.w_flag_container, flagView);
    }
  }
  
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
}
